package platform

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"gitee.com/wangshh_123/cross-pay-go/src/errors"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/integration"
	common "gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
)

// UnifiedTransactionController 统一交易控制器
type UnifiedTransactionController struct {
	platformManager *integration.PlatformManager
}

// NewUnifiedTransactionController 创建统一交易控制器
func NewUnifiedTransactionController(platformManager *integration.PlatformManager) *UnifiedTransactionController {
	return &UnifiedTransactionController{
		platformManager: platformManager,
	}
}

// validatePlatform 验证平台类型
func (c *UnifiedTransactionController) validatePlatform(platformType string) error {
	supportedPlatforms := []string{"photonpay", "hlpay"}
	for _, platform := range supportedPlatforms {
		if platform == platformType {
			return nil
		}
	}
	return errors.NewAppError(http.StatusBadRequest, "unsupported_platform", nil)
}

// validateTransactionID 验证交易ID
func (c *UnifiedTransactionController) validateTransactionID(transactionID string) error {
	if transactionID == "" {
		return errors.NewAppError(http.StatusBadRequest, "transaction_id_required", nil)
	}
	if len(transactionID) > 100 {
		return errors.NewAppError(http.StatusBadRequest, "transaction_id_too_long", nil)
	}
	// 验证交易ID格式（只允许字母、数字、下划线、连字符）
	for _, char := range transactionID {
		if !((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') ||
			(char >= '0' && char <= '9') || char == '_' || char == '-') {
			return errors.NewAppError(http.StatusBadRequest, "invalid_transaction_id_format", nil)
		}
	}
	return nil
}

// validateBatchOpenCardRequest 验证批量开卡请求
func (c *UnifiedTransactionController) validateBatchOpenCardRequest(req *platformCommon.BatchOpenCardRequest) error {
	// 验证BIN号
	if req.CardBin == "" && req.Bin == "" {
		return errors.NewAppError(http.StatusBadRequest, "bin_required", fmt.Errorf("either 'bin' or 'cardBin' field is required"))
	}

	// 验证持卡人ID
	if req.CardholderID == "" || req.CardholderID == "undefined" {
		return errors.NewAppError(http.StatusBadRequest, "invalid_cardholder_id", fmt.Errorf("cardholderId is required and cannot be 'undefined'"))
	}

	// 验证卡币种
	if req.CardCurrency == "" {
		return errors.NewAppError(http.StatusBadRequest, "card_currency_required", nil)
	}

	// 验证卡类型
	if req.CardType == "" {
		return errors.NewAppError(http.StatusBadRequest, "card_type_required", nil)
	}

	// 验证开卡数量
	if req.CardCount < 1 || req.CardCount > 100 {
		return errors.NewAppError(http.StatusBadRequest, "invalid_card_count", fmt.Errorf("cardCount must be between 1 and 100"))
	}

	// 验证超时时间
	if req.TimeoutSeconds < 1 || req.TimeoutSeconds > 300 {
		return errors.NewAppError(http.StatusBadRequest, "invalid_timeout_seconds", fmt.Errorf("timeoutSeconds must be between 1 and 300"))
	}

	// 验证请求ID
	if req.RequestID == "" {
		return errors.NewAppError(http.StatusBadRequest, "request_id_required", nil)
	}
	if len(req.RequestID) > 100 {
		return errors.NewAppError(http.StatusBadRequest, "request_id_too_long", nil)
	}

	// 验证金额字段（如果存在）
	if req.Cost < 0 {
		return errors.NewAppError(http.StatusBadRequest, "invalid_cost", fmt.Errorf("cost cannot be negative"))
	}

	// 验证充值金额（如果存在）
	if req.RechargeAmount != "" {
		if _, err := strconv.ParseFloat(req.RechargeAmount, 64); err != nil {
			return errors.NewAppError(http.StatusBadRequest, "invalid_recharge_amount", err)
		}
	}

	// 验证到账金额（如果存在）
	if req.ArrivalAmount != "" {
		if _, err := strconv.ParseFloat(req.ArrivalAmount, 64); err != nil {
			return errors.NewAppError(http.StatusBadRequest, "invalid_arrival_amount", err)
		}
	}

	return nil
}

// GetTransactionList 获取交易列表
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *UnifiedTransactionController) GetTransactionList(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 验证平台类型
	if err := c.validatePlatform(platformInfo.PlatformType); err != nil {
		appErr := err.(*errors.AppError)
		common.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 解析查询参数
	var request platformCommon.TransactionListRequest
	if err := ctx.ShouldBindQuery(&request); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证分页参数
	if request.PageIndex < 1 {
		request.PageIndex = 1
	}
	if request.PageSize < 1 || request.PageSize > 100 {
		request.PageSize = 10
	}

	// 验证查询参数
	if request.CardID != "" && len(request.CardID) > 50 {
		common.Error(ctx, http.StatusBadRequest, "card_id_too_long", nil)
		return
	}

	if request.CardNo != "" && len(request.CardNo) > 50 {
		common.Error(ctx, http.StatusBadRequest, "card_no_too_long", nil)
		return
	}

	// 验证状态参数
	if request.Status != "" {
		validStatuses := []string{"success", "failed", "pending", "cancelled", "processing"}
		isValid := false
		for _, validStatus := range validStatuses {
			if strings.ToLower(request.Status) == validStatus {
				isValid = true
				break
			}
		}
		if !isValid {
			common.Error(ctx, http.StatusBadRequest, "invalid_status", nil)
			return
		}
	}

	// 验证交易类型参数
	if request.TransactionType != "" {
		validTypes := []string{"purchase", "refund", "recharge", "withdraw", "transfer", "fee"}
		isValid := false
		for _, validType := range validTypes {
			if strings.ToLower(request.TransactionType) == validType {
				isValid = true
				break
			}
		}
		if !isValid {
			common.Error(ctx, http.StatusBadRequest, "invalid_transaction_type", nil)
			return
		}
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformInfo.PlatformType, "transaction_list", &request)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_transaction_list_failed", err)
		return
	}

	// 返回成功响应
	common.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// GetTransactionDetail 获取交易详情
// 根据用户的平台类型自动选择对应的平台进行查询
func (c *UnifiedTransactionController) GetTransactionDetail(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 验证平台类型
	if err := c.validatePlatform(platformInfo.PlatformType); err != nil {
		appErr := err.(*errors.AppError)
		common.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 解析查询参数
	transactionID := ctx.Query("transactionId")

	// 验证交易ID
	if err := c.validateTransactionID(transactionID); err != nil {
		appErr := err.(*errors.AppError)
		common.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	request := &platformCommon.TransactionDetailRequest{
		TransactionID: transactionID,
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformInfo.PlatformType, "transaction_detail", request)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_transaction_detail_failed", err)
		return
	}

	// 返回成功响应
	common.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}

// BatchOpenCard 批量开卡
// 根据用户的平台类型自动选择对应的平台进行批量开卡
func (c *UnifiedTransactionController) BatchOpenCard(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 验证平台类型
	if err := c.validatePlatform(platformInfo.PlatformType); err != nil {
		appErr := err.(*errors.AppError)
		common.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 解析请求参数
	var request platformCommon.BatchOpenCardRequest
	if err := ctx.ShouldBindJSON(&request); err != nil {
		common.Error(ctx, http.StatusBadRequest, "invalid_params", err)
		return
	}

	// 验证请求参数
	if err := c.validateBatchOpenCardRequest(&request); err != nil {
		appErr := err.(*errors.AppError)
		common.Error(ctx, appErr.Code, appErr.Message, nil)
		return
	}

	// 设置默认开卡数量为1
	if request.CardCount <= 0 {
		request.CardCount = 1
	}

	// 设置默认超时时间为15秒
	if request.TimeoutSeconds <= 0 {
		request.TimeoutSeconds = 15
	}

	// 使用工厂模式处理请求
	result, err := c.platformManager.HandleRequestWithGinContext(ctx, platformInfo.PlatformType, "batch_open_card", &request)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "batch_open_card_failed", err)
		return
	}

	// 返回成功响应
	common.Success(ctx, gin.H{
		"platform": platformInfo.PlatformType,
		"data":     result,
	})
}
